package com.example.controller;

import com.example.dto.LoginRequestDTO;
import com.example.dto.Response;
import com.example.security.CustomAuthenticationToken;
import com.example.service.CustomUserDetailsService;
import com.example.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public Response<String> login(@RequestBody LoginRequestDTO loginRequest) {
        try {
            // 使用 AuthenticationManager 调用自定义的 AuthenticationProvider 进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

            // 生成 JWT Token
            String token = jwtUtil.generateToken(authentication.getName());

            // 使用加密后的用户名 (tokenIdentifier) 作为 Redis 键存储 UID
            String tokenIdentifier = jwtUtil.hashIdentifier(authentication.getName());
            redisTemplate.opsForValue().set("auth:user:uid:" + tokenIdentifier, ((CustomAuthenticationToken) authentication).getUid());

            return Response.success(token);
        } catch (AuthenticationException e) {
            throw new RuntimeException("Invalid credentials");
        }
    }

    @PostMapping("/logout")
    public Response<Boolean> logout(@RequestParam String token) {
        // 验证 Token 并获取 Claims
        Claims claims = jwtUtil.validateToken(token);
        if (claims == null || jwtUtil.isTokenExpired(claims)) {
            return Response.success(false);
        }

        // 获取加密后的用户名（tokenIdentifier）
        String tokenIdentifier = claims.getSubject();

        if (tokenIdentifier != null && !tokenIdentifier.isEmpty()) {
            // 使用加密后的用户名作为 Redis 键，移除对应的 UID
            String uidKey = "auth:user:uid:" + tokenIdentifier;
            redisTemplate.delete(uidKey);

            return Response.success(true);
        }

        return Response.success(false);
    }

}
